package userlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/slice"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpUserStatusLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpUserStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpUserStatusLogic {
	return &UpUserStatusLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpUserStatusLogic) UpUserStatus(in *syspb.UpUserStatusReq) (*syspb.UpUserStatusResp, error) {
	if in.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新用户状态失败：参数缺失"),
			tool.GetErrMsgFormat("update user status"), "params is not existed", in)
	}

	// 判断是否是超级管理员
	uidList := l.svcCtx.Config.SystemCustom.NotCheckAuthUserIds
	if slice.Contain(uidList, in.GetId()) {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新用户状态失败：不允许操作超级管理员"),
			tool.GetErrMsgFormat("update user status"), "user is admin", in)
	}

	// 查询出用户信息
	one, err := l.svcCtx.SysUserModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update user status"), err, in)
	}
	one.UserStatus = in.GetUserStatus()
	one.UpdateUser = in.GetUpdateUser()

	// 更新
	err = l.svcCtx.SysUserModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update user status"), err, in)
	}

	return &syspb.UpUserStatusResp{}, nil
}
